<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>swift常用高阶函数 | Albert Yuan's Blog</title><meta name="keywords" content="swift"><meta name="author" content="Albert Yuan"><meta name="copyright" content="Albert Yuan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="referrer" content="no-referrer"><meta name="description" content="filter过滤器（起到筛选作用）:可以取出数组中符合条件的元素，重新组成一个新的数组（Return an Array containing the elements of self, in order, that satisfy the predicate includeElement）  Array类的filter方法用于筛选，其定义是：filter(includeElement: (T) -">
<meta property="og:type" content="article">
<meta property="og:title" content="swift常用高阶函数">
<meta property="og:url" content="https://yllove.gitee.io/2021/08/17/Swift/swift%E5%B8%B8%E7%94%A8%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/index.html">
<meta property="og:site_name" content="Albert Yuan&#39;s Blog">
<meta property="og:description" content="filter过滤器（起到筛选作用）:可以取出数组中符合条件的元素，重新组成一个新的数组（Return an Array containing the elements of self, in order, that satisfy the predicate includeElement）  Array类的filter方法用于筛选，其定义是：filter(includeElement: (T) -">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170726%2Fdb846e50a1184decb5e9476280bb36d3_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631788568&t=a93d0356049a3568c65cf59d16ef1943">
<meta property="article:published_time" content="2021-08-17T09:12:35.732Z">
<meta property="article:modified_time" content="2022-03-28T10:09:06.430Z">
<meta property="article:author" content="Albert Yuan">
<meta property="article:tag" content="Swift">
<meta property="article:tag" content="函数式编程">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170726%2Fdb846e50a1184decb5e9476280bb36d3_th.jpg&refer=http%3A%2F%2Fimg.mp.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631788568&t=a93d0356049a3568c65cf59d16ef1943"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://yllove.gitee.io/2021/08/17/Swift/swift%E5%B8%B8%E7%94%A8%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: {"appId":"X8NS0XSX99","apiKey":"b9d4530647c8b5bf7928a04c47752ad7","indexName":"albertyuan","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://fastly.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'swift常用高阶函数',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2022-03-28 18:09:06'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/blog/atom.xml" title="Albert Yuan's Blog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170726%2Fdb846e50a1184decb5e9476280bb36d3_th.jpg&amp;refer=http%3A%2F%2Fimg.mp.itc.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1631788568&amp;t=a93d0356049a3568c65cf59d16ef1943')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Albert Yuan's Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">swift常用高阶函数</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-08-17T09:12:35.732Z" title="发表于 2021-08-17 17:12:35">2021-08-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-03-28T10:09:06.430Z" title="更新于 2022-03-28 18:09:06">2022-03-28</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/Swift/">Swift</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="swift常用高阶函数"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h4 id="filter"><a href="#filter" class="headerlink" title="filter"></a>filter</h4><p>过滤器（起到筛选作用）:可以取出数组中符合条件的元素，重新组成一个新的数组（Return an <code>Array</code> containing the elements of <code>self</code>, in order, that satisfy the predicate <code>includeElement</code>）</p>
<blockquote>
<p>Array类的filter方法用于筛选，其定义是：filter(includeElement: (T) -&gt; Bool) -&gt; T[] ;<strong>传入的参数是一个闭包。当你在调用filter的时候，实际上是通过传入的这个includeElement去访问了Array内部的变量，并做相应的处理</strong>。</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> strTest:[<span class="type">String</span>] <span class="operator">=</span> [<span class="type">String</span>]()</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="number">0</span><span class="operator">..&lt;</span><span class="number">1000000</span> &#123;</span><br><span class="line">  strTest.append(<span class="string">&quot;A<span class="subst">\(i)</span>&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">$0代表传入的元素本身，而不是下标</span></span><br><span class="line"><span class="comment">返回的是一个数组，所以取具体值时需要给下标</span></span><br><span class="line"><span class="comment">filter实际上也是在做循环遍历，把断点打到filter这句话上，断点会反复中断</span></span><br><span class="line"><span class="comment">尾随闭包的形式调用filler</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">let</span> res <span class="operator">=</span> strTest.filter&#123;<span class="variable">$0</span> <span class="operator">==</span> <span class="string">&quot;A50&quot;</span>&#125; </span><br><span class="line"><span class="built_in">print</span>(res[<span class="number">0</span>]) <span class="comment">// A50</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> strTest1:[(<span class="type">Int</span>, <span class="type">String</span>)] <span class="operator">=</span> [(<span class="type">Int</span>, <span class="type">String</span>)]()</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="number">0</span><span class="operator">..&lt;</span><span class="number">1000000</span> &#123;</span><br><span class="line">  strTest1.append((i, <span class="string">&quot;A<span class="subst">\(i)</span>&quot;</span>))</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//$0.0代表传入的元组的第一个值，如果元组被命名过了，则可以直接带名字</span></span><br><span class="line"><span class="built_in">print</span>(strTest1.filter(&#123;<span class="variable">$0</span>.<span class="number">0</span> <span class="operator">==</span> <span class="number">250</span>&#125;)[<span class="number">0</span>].<span class="number">1</span>)   <span class="comment">//A250</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="map"><a href="#map" class="headerlink" title="map"></a>map</h4><p>转换器（映射操作）：map<code>函数作用于</code>Collection<code>中的每一个元素，然后返回一个新的</code>经过映射关系处理过的 Collection（Return an <code>Array</code> containing the results of <strong>mapping <code>transform</code></strong> over <code>self</code>.）</p>
<blockquote>
<ul>
<li><code>map</code>函数可以对数组中的每一个元素做一次处理，如同遍历的作用</li>
<li><code>map</code>函数接受一个闭包作为参数， 然后它会遍历整个数组，并对数组中每一个元素执行闭包中定义的操作。 相当于对数组中的所有元素做了一个映射</li>
<li><code>map</code>函数可以对一个集合类型的所有元素做一个映射操作</li>
<li><code>map</code>函数不会修改实例值， 而是<strong>新建一个拷贝</strong></li>
</ul>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> cast <span class="operator">=</span> [<span class="string">&quot;Vivien&quot;</span>, <span class="string">&quot;Marlon&quot;</span>, <span class="string">&quot;Kim&quot;</span>, <span class="string">&quot;Karl&quot;</span>]</span><br><span class="line"><span class="keyword">let</span> lowercaseNames <span class="operator">=</span> cast.map &#123; <span class="variable">$0</span>.lowercased() &#125;</span><br><span class="line"><span class="comment">// &#x27;lowercaseNames&#x27; == [&quot;vivien&quot;, &quot;marlon&quot;, &quot;kim&quot;, &quot;karl&quot;]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> letterCounts <span class="operator">=</span> cast.map &#123; <span class="variable">$0</span>.count &#125;</span><br><span class="line"><span class="comment">// &#x27;letterCounts&#x27; == [6, 6, 3, 4]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/// 第一次返回的是数组，也可以map连写</span></span><br><span class="line"><span class="keyword">let</span> res <span class="operator">=</span> cast.map&#123; (str) -&gt; <span class="type">String</span> <span class="keyword">in</span></span><br><span class="line">    str.lowercased()</span><br><span class="line">    &#125;.map &#123; (str) -&gt; <span class="type">Int</span> <span class="keyword">in</span></span><br><span class="line">        str.count</span><br><span class="line">    &#125;<span class="comment">// &#x27;res&#x27; = [6, 6, 3, 4]</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//类型推断省略参数类型与返回值类型</span></span><br><span class="line"><span class="keyword">let</span> res1 <span class="operator">=</span> cast.map&#123; </span><br><span class="line">    <span class="variable">$0</span>.lowercased()</span><br><span class="line">    &#125;.map &#123;</span><br><span class="line">        <span class="variable">$0</span>.count</span><br><span class="line">&#125;<span class="comment">// &#x27;res1&#x27; = [6, 6, 3, 4]</span></span><br></pre></td></tr></table></figure>

<p>源码解析：可以看出<code>map</code>函数本质是创建新的数组，对集合内的每个元素进行<code>transform</code>操作（闭包表达式），然后返回新数组</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/// - Parameter transform: A mapping closure. `transform` accepts an</span></span><br><span class="line"><span class="comment">///   element of this sequence as its parameter and returns a transformed</span></span><br><span class="line"><span class="comment">///   value of the same or of a different type.</span></span><br><span class="line"><span class="comment">/// - Returns: An array containing the transformed elements of this</span></span><br><span class="line"><span class="comment">///   sequence.</span></span><br><span class="line"><span class="comment">///</span></span><br><span class="line"><span class="comment">/// - Complexity: O(*n*), where *n* is the length of the sequence.</span></span><br><span class="line"><span class="keyword">@inlinable</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">func</span> <span class="title function_">map</span>&lt;<span class="type">T</span>&gt;(</span><br><span class="line">  <span class="keyword">_</span> <span class="params">transform</span>: (<span class="type">Element</span>) <span class="keyword">throws</span> -&gt; <span class="type">T</span></span><br><span class="line">) <span class="keyword">rethrows</span> -&gt; [<span class="type">T</span>] &#123;</span><br><span class="line">  <span class="keyword">let</span> initialCapacity <span class="operator">=</span> underestimatedCount</span><br><span class="line">  <span class="keyword">var</span> result <span class="operator">=</span> <span class="type">ContiguousArray</span>&lt;<span class="type">T</span>&gt;()</span><br><span class="line">  result.reserveCapacity(initialCapacity)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> iterator <span class="operator">=</span> <span class="keyword">self</span>.makeIterator()</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Add elements up to the initial capacity without checking for regrowth.</span></span><br><span class="line">  <span class="keyword">for</span> <span class="keyword">_</span> <span class="keyword">in</span> <span class="number">0</span><span class="operator">..&lt;</span>initialCapacity &#123;</span><br><span class="line">    result.append(<span class="keyword">try</span> transform(iterator.next()<span class="operator">!</span>))</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Add remaining elements, if any.</span></span><br><span class="line">  <span class="keyword">while</span> <span class="keyword">let</span> element <span class="operator">=</span> iterator.next() &#123;</span><br><span class="line">    result.append(<span class="keyword">try</span> transform(element))</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="type">Array</span>(result)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>map是串行执行的，在处理大量数据时会有一点的性能问题，我们可以尝试通过extension自定义一个并行的map函数：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//自定义并行的map操作</span></span><br><span class="line"><span class="keyword">extension</span> <span class="title class_">Array</span> <span class="title class_">where</span> <span class="title class_">Element</span>:<span class="title class_">Any</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">func</span> <span class="title function_">concurrentMap</span>&lt;<span class="type">T</span>&gt;(<span class="keyword">_</span> <span class="params">transform</span>:(<span class="type">Element</span>) -&gt; <span class="type">T</span>) -&gt; [<span class="type">T</span>] &#123;</span><br><span class="line">        <span class="keyword">let</span> n <span class="operator">=</span> <span class="keyword">self</span>.count</span><br><span class="line">        <span class="keyword">if</span> n <span class="operator">==</span> <span class="number">0</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> []</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">var</span> result <span class="operator">=</span> <span class="type">Array</span>&lt;<span class="type">T</span>&gt;()</span><br><span class="line">        result.reserveCapacity(n)</span><br><span class="line"></span><br><span class="line">        <span class="comment">//如果不使用安全锁是非线程安全:存在丢失元素问题</span></span><br><span class="line">        <span class="type">DispatchQueue</span>.concurrentPerform(iterations: n) &#123; (i) <span class="keyword">in</span></span><br><span class="line">            objc_sync_enter(n)</span><br><span class="line">            result.append(transform(<span class="keyword">self</span>[i]))</span><br><span class="line">            objc_sync_exit(n)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<hr>
<h4 id="flatMap"><a href="#flatMap" class="headerlink" title="flatMap"></a>flatMap</h4><p>相比较<code>map</code>函数来说，<code>flatMap</code>函数最主要的两个作用一个是“压平”（降维），一个是过滤<code>nil</code>值</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//二维数组“压平”</span></span><br><span class="line"><span class="keyword">let</span> nums <span class="operator">=</span> [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]]</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> result1 <span class="operator">=</span> nums.map&#123;<span class="variable">$0</span>&#125;</span><br><span class="line"><span class="keyword">var</span> result2 <span class="operator">=</span> nums.flatMap&#123;<span class="variable">$0</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;map：<span class="subst">\(result1)</span>&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;flatMap：<span class="subst">\(result2)</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//输出以下内容</span></span><br><span class="line"><span class="comment">//map：[[1, 2, 3], [4, 5, 6]]</span></span><br><span class="line"><span class="comment">//flatMap：[1, 2, 3, 4, 5, 6]</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//过滤nil值</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">使用map函数，数组内元素变为Optional类型，同时nil值也被保留。</span></span><br><span class="line"><span class="comment">使用flatMap函数，会把数组内元素进行Optional解包，并且过滤nil值</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">let</span> strings <span class="operator">=</span> [<span class="string">&quot;HANK&quot;</span>, <span class="string">&quot;CAT&quot;</span>, <span class="string">&quot;Kody&quot;</span>, <span class="string">&quot;COOCI&quot;</span>, <span class="literal">nil</span>]</span><br><span class="line"><span class="keyword">var</span> result1 <span class="operator">=</span> strings.map&#123;<span class="variable">$0</span>&#125;</span><br><span class="line"><span class="keyword">var</span> result2 <span class="operator">=</span> strings.flatMap&#123;<span class="variable">$0</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;map：<span class="subst">\(result1)</span>&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;flatMap：<span class="subst">\(result2)</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//输出以下内容</span></span><br><span class="line"><span class="comment">//map：[Optional(&quot;HANK&quot;), Optional(&quot;CAT&quot;), Optional(&quot;Kody&quot;), Optional(&quot;COOCI&quot;), nil]</span></span><br><span class="line"><span class="comment">//flatMap：[&quot;HANK&quot;, &quot;CAT&quot;, &quot;Kody&quot;, &quot;COOCI&quot;]</span></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="compactmap"><a href="#compactmap" class="headerlink" title="compactmap"></a>compactmap</h4><blockquote>
<p>过滤空值</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> emptyArr1 <span class="operator">=</span> [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="literal">nil</span>,<span class="number">4</span>,<span class="number">5</span>]</span><br><span class="line"><span class="keyword">let</span> newemptyArr1 <span class="operator">=</span> emptyArr1.compactMap&#123;<span class="variable">$0</span><span class="operator">+</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(newemptyArr1)</span><br><span class="line"><span class="comment">//[1, 2, 3, 4, 5]</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>取出数组对象元素中指定属性，并构成一个新的属性数组</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> all <span class="operator">=</span> changeData.normalItem<span class="operator">?</span>.filter&#123;<span class="variable">$0</span>.sel <span class="operator">==</span> <span class="literal">true</span>&#125;</span><br><span class="line"><span class="keyword">let</span> resultStr <span class="operator">=</span> all<span class="operator">?</span>.compactMap(&#123;<span class="variable">$0</span>.tit&#125;).joined(separator: <span class="string">&quot;,&quot;</span>) <span class="operator">??</span> <span class="string">&quot;&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="reduce"><a href="#reduce" class="headerlink" title="reduce"></a>reduce</h4><blockquote>
<p>累计操作（加减乘除）,可设置初始计算值</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> numberarr1 <span class="operator">=</span> [<span class="number">2</span>,<span class="number">4</span>,<span class="number">6</span>,<span class="number">8</span>,<span class="number">10</span>]</span><br><span class="line"><span class="keyword">let</span> sult <span class="operator">=</span> numberarr1.reduce(<span class="number">1</span>) &#123; <span class="variable">$0</span> <span class="operator">*</span> <span class="variable">$1</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(sult)</span><br><span class="line"><span class="comment">//3840</span></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="zip"><a href="#zip" class="headerlink" title="zip"></a>zip</h4><blockquote>
<p>将两个数组合并成一个新的元组数组</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span>  names <span class="operator">=</span> [ <span class="string">&quot;Apple&quot;</span> ,  <span class="string">&quot;Pear&quot;</span> ]</span><br><span class="line"><span class="keyword">let</span>  prices <span class="operator">=</span> [<span class="number">7</span>, <span class="number">6</span>]</span><br><span class="line"><span class="keyword">let</span>  dict <span class="operator">=</span>  <span class="type">Dictionary</span> (uniqueKeysWithValues: <span class="built_in">zip</span>(names, prices))</span><br><span class="line">print (dict)</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="joined"><a href="#joined" class="headerlink" title="joined"></a>joined</h4><blockquote>
<p>将序列以分隔符串联起来成为字符串</p>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// MARK: ---------- joined //将序列以分隔符串联起来成为字符串</span></span><br><span class="line"><span class="built_in">print</span>([<span class="string">&quot;A&quot;</span>, <span class="string">&quot;B&quot;</span>, <span class="string">&quot;C&quot;</span>].joined(separator: <span class="string">&quot;:&quot;</span>))</span><br><span class="line"><span class="comment">//&quot;A:B:C&quot;</span></span><br></pre></td></tr></table></figure>



<hr>
<h3 id="高阶函数的使用案例"><a href="#高阶函数的使用案例" class="headerlink" title="高阶函数的使用案例"></a>高阶函数的使用案例</h3><p>需求：查找一段话中每个单词出现的次数</p>
<p>命令式编程风格：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//无意义单词数组</span></span><br><span class="line"><span class="keyword">let</span> <span class="type">Now_Words</span> <span class="operator">=</span> [<span class="string">&quot;am&quot;</span>, <span class="string">&quot;is&quot;</span>, <span class="string">&quot;are&quot;</span>,<span class="string">&quot;a&quot;</span>, <span class="string">&quot;the&quot;</span>,<span class="string">&quot;that&quot;</span>,<span class="string">&quot;this&quot;</span>,<span class="string">&quot;there&quot;</span>,<span class="string">&quot;here&quot;</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">//命令式编程风格： 迫使我们处于性能考虑，把不同的任务交织起来，以便能够用一次循环完成多个任务</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">wordFreq</span>(<span class="params">words</span>: <span class="type">String</span>) -&gt; [<span class="type">String</span> : <span class="type">Int</span>] &#123;</span><br><span class="line">    <span class="keyword">var</span> wordDic: [<span class="type">String</span> :<span class="type">Int</span>] <span class="operator">=</span> [:]</span><br><span class="line">    <span class="keyword">let</span> wordlist <span class="operator">=</span> words.split(separator: <span class="string">&quot; &quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> word <span class="keyword">in</span> wordlist &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span>  lowerword <span class="operator">=</span> word.lowercased()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> <span class="operator">!</span><span class="type">Now_Words</span>.contains(lowerword)  &#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">let</span> count <span class="operator">=</span> wordDic[lowerword] &#123;</span><br><span class="line"></span><br><span class="line">                wordDic[lowerword] <span class="operator">=</span> count <span class="operator">+</span> <span class="number">1</span></span><br><span class="line"></span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line"></span><br><span class="line">                wordDic[lowerword] <span class="operator">=</span> <span class="number">1</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> wordDic</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> longstr <span class="operator">=</span> <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">In Swift, enumeration types are first-class types. They use many features that are traditionally only supported by classes, such as computed properties, which are used to provide additional information about enumerated values, and instance methods, which are used to provide and enumerate values. Associated functions. Enumerations can also define constructors (initializers) to provide an initial value; they can extend their functions on the basis of the original implementation; they can also follow protocols to provide standard functions.</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">let</span> redic <span class="operator">=</span> wordFreq(words: longstr)</span><br></pre></td></tr></table></figure>

<p>使用高阶函数实现函数式编程：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="type">Now_Words</span> <span class="operator">=</span> [<span class="string">&quot;am&quot;</span>, <span class="string">&quot;is&quot;</span>, <span class="string">&quot;are&quot;</span>,<span class="string">&quot;a&quot;</span>, <span class="string">&quot;the&quot;</span>,<span class="string">&quot;that&quot;</span>,<span class="string">&quot;this&quot;</span>,<span class="string">&quot;there&quot;</span>,<span class="string">&quot;here&quot;</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用高阶函数将不同功能解放出来，让我们能站在更高的抽象层次上去考虑问题，把问题看到更加清楚</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">wordFreq2</span>(<span class="params">words</span>: <span class="type">String</span>) -&gt; [<span class="type">String</span> : <span class="type">Int</span>] &#123;</span><br><span class="line">    <span class="keyword">var</span> wordDic <span class="operator">=</span> [<span class="type">String</span> :<span class="type">Int</span>]()</span><br><span class="line">    <span class="keyword">let</span> wordlist <span class="operator">=</span> words.split(separator: <span class="string">&quot; &quot;</span>)</span><br><span class="line">  <span class="comment">//映射转换</span></span><br><span class="line">    wordlist.map&#123;<span class="variable">$0</span>.lowercased()&#125;</span><br><span class="line">	<span class="comment">//条件过滤</span></span><br><span class="line">        .filter&#123; <span class="operator">!</span><span class="type">Now_Words</span>.contains(<span class="variable">$0</span>)&#125;</span><br><span class="line">	<span class="comment">//循环遍历</span></span><br><span class="line">        .forEach &#123; (word) <span class="keyword">in</span></span><br><span class="line">            wordDic[word] <span class="operator">=</span> (wordDic[word] <span class="operator">??</span> <span class="number">0</span>) <span class="operator">+</span> <span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">    <span class="keyword">return</span> wordDic</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">print</span>(wordFreq2(words: longstr))</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Albert Yuan</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yllove.gitee.io/2021/08/17/Swift/swift%E5%B8%B8%E7%94%A8%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/">https://yllove.gitee.io/2021/08/17/Swift/swift%E5%B8%B8%E7%94%A8%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yllove.gitee.io" target="_blank">Albert Yuan's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/Swift/">Swift</a><a class="post-meta__tags" href="/blog/tags/%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/">函数式编程</a></div><div class="post_share"><div class="social-share" data-image="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170726%2Fdb846e50a1184decb5e9476280bb36d3_th.jpg&amp;refer=http%3A%2F%2Fimg.mp.itc.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1631788568&amp;t=a93d0356049a3568c65cf59d16ef1943" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/08/17/Swift/swift%E7%BB%A7%E6%89%BF/"><img class="prev-cover" src= "" data-lazy-src="https://pic1.zhimg.com/v2-4886a69d700e9e441306cddbb8e4bc13_qhd.jpg" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">swift继承</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/08/18/Swift/swift%E6%9E%84%E9%80%A0%E8%BF%87%E7%A8%8B/"><img class="next-cover" src= "" data-lazy-src="https://docs.swift.org/swift-book/_images/initializerDelegation02_2x.png" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">swift构造过程与析构过程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2021/11/23/Swift/swift编译流程/" title="swift编译流程"><img class="cover" src= "" data-lazy-src="/blog/img/defaultCover.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-11-23</div><div class="title">swift编译流程</div></div></a></div><div><a href="/blog/2022/03/29/Swift/Swift-SwiftyJSON的使用详解/Swift-SwiftyJSON的使用详解/" title="Swift-SwiftyJSON的使用详解"><img class="cover" src= "" data-lazy-src="/blog/img/defaultCover.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-03-29</div><div class="title">Swift-SwiftyJSON的使用详解</div></div></a></div><div><a href="/blog/2022/04/06/Swift/swift-snap布局总结/swift-snap布局总结/" title="swift-snap布局总结"><img class="cover" src= "" data-lazy-src="/blog/img/defaultCover.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-06</div><div class="title">swift-snap布局总结</div></div></a></div><div><a href="/blog/2021/08/17/RxSwift/RxSwift初识/" title="RxSwift初识"><img class="cover" src= "" data-lazy-src="https://miro.medium.com/max/1400/1*WvSoiQrJV0Bjpau2_s9fmw.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-17</div><div class="title">RxSwift初识</div></div></a></div><div><a href="/blog/2021/09/15/RxSwift/RxSwift的使用详解1/" title="RxSwift的使用详解1"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018010609150332714.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-15</div><div class="title">RxSwift的使用详解1</div></div></a></div><div><a href="/blog/2021/09/17/RxSwift/RxSwift的使用详解10-条件和布尔操作符/" title="RxSwift的使用详解10-条件和布尔操作符"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018012419380031551.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-17</div><div class="title">RxSwift的使用详解10-条件和布尔操作符</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Albert Yuan</div><div class="author-info__description">博学之,审问之,慎思之,明辨之,笃行之</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/yuanliangYL"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yuanliangYL" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:yuanliangios@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="qq:1023817403" target="_blank" title="QQ"><i class="fab fa-qq"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">love cat , love life</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#filter"><span class="toc-text">filter</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#map"><span class="toc-text">map</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#flatMap"><span class="toc-text">flatMap</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#compactmap"><span class="toc-text">compactmap</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#reduce"><span class="toc-text">reduce</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#zip"><span class="toc-text">zip</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#joined"><span class="toc-text">joined</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0%E7%9A%84%E4%BD%BF%E7%94%A8%E6%A1%88%E4%BE%8B"><span class="toc-text">高阶函数的使用案例</span></a></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包"><img src= "" data-lazy-src="https://img.mp.itc.cn/upload/20170409/1a8f793d7282451cbd1beb6841608c90_th.jpeg" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 自定义网页下载IPA包"/></a><div class="content"><a class="title" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包">iOS 自定义网页下载IPA包</a><time datetime="2023-02-07T02:46:29.851Z" title="更新于 2023-02-07 10:46:29">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS"><img src= "" data-lazy-src="https://pic4.zhimg.com/v2-6a115fea4db1ad770dccf4119bfab36f_1440w.jpg?source=172ae18b" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="flutter接入原生-iOS"/></a><div class="content"><a class="title" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS">flutter接入原生-iOS</a><time datetime="2023-02-07T01:18:53.661Z" title="更新于 2023-02-07 09:18:53">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP"><img src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.winwin7.com%2Fuploadfile%2F2021%2F0114%2F20210114141748239.jpg&amp;refer=http%3A%2F%2Fwww.winwin7.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1673854539&amp;t=aad2108ffb799b04e94a28cc58f038f1" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 如何在模拟器中安装APP"/></a><div class="content"><a class="title" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP">iOS 如何在模拟器中安装APP</a><time datetime="2022-12-17T07:48:56.594Z" title="更新于 2022-12-17 15:48:56">2022-12-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库"><img src= "" data-lazy-src="https://photos.infinum.com/store/b558bd40787ecad225d9c66322f14522" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="swift常用三方库"/></a><div class="content"><a class="title" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库">swift常用三方库</a><time datetime="2022-12-16T06:37:20.115Z" title="更新于 2022-12-16 14:37:20">2022-12-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup"><img src= "" data-lazy-src="/blog/img/defaultCover.png" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="GCD进阶之DispatchWorkItem和DispatchGroup"/></a><div class="content"><a class="title" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup">GCD进阶之DispatchWorkItem和DispatchGroup</a><time datetime="2022-12-12T07:19:37.277Z" title="更新于 2022-12-12 15:19:37">2022-12-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170726%2Fdb846e50a1184decb5e9476280bb36d3_th.jpg&amp;refer=http%3A%2F%2Fimg.mp.itc.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1631788568&amp;t=a93d0356049a3568c65cf59d16ef1943')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Albert Yuan</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcom to my  blog</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://fastly.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/blog/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://fastly.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'REc8eytE1gJDl3d8FkudLNlL-gzGzoHsz',
      appKey: 'gGO3y8I9oVlc4Cd5N1fizNPW',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://fastly.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="255,0,0" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>